package com.abcdefg.webpagechatprojectbymyself.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnlineUserMessage {
    //此处使用ConcurrentHashMap保证哈希表线程安全
    private ConcurrentHashMap<Integer, WebSocketSession> onlineUsers = new ConcurrentHashMap<>();

    //客户端上线
    public void online(Integer userId, WebSocketSession session) {
        if(onlineUsers.get(userId) !=null){
            //此时说明用户已经上线，就不记录用户这个映射关系
            //防止多开
            return;
        }
        onlineUsers.put(userId, session);
    }
    //客户端下线
    public void offline(Integer userId, WebSocketSession session) {
        //此处针对多开的特殊处理
        if(onlineUsers.get(userId)==session){
            onlineUsers.remove(userId);
        }
    }

    //根据userId获取WebSocketSession
    public WebSocketSession getOnlineUser(Integer userId)  {
        return onlineUsers.get(userId);
    }
}
